package com.itmuch.box.controller.common;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.itmuch.box.core.base.BaseController;
import com.itmuch.box.core.exception.BusinessException;
import com.itmuch.box.domain.attach.entity.Attach;
import com.itmuch.box.service.attach.AttachService;

@Controller
@RequestMapping("/${uploadPath}")
public class FileDownloadController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileDownloadController.class);
    @Autowired
    private AttachService attachService;

    /**
     * 文件下载
     * 参考: http://stackoverflow.com/questions/5690228/spring-mvc-how-to-return-image-in-responsebody
     * @param projectCode
     * @param memberId
     * @param dateStr
     * @param uuid
     * @param extension
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/{projectCode}/{memberId}/{dateStr}/{uuid}.{extension}")
    public void download(@PathVariable String projectCode, @PathVariable Integer memberId, @PathVariable String dateStr, @PathVariable String uuid,
            @PathVariable String extension, HttpServletRequest req, HttpServletResponse resp) {

        String fileInDisk = String.format("%s/%s/%s/%s/%s/%s.%s", this.attachLocation, this.uploadPath, projectCode, memberId, dateStr, uuid,
                extension);
        File file = new File(fileInDisk);
        String userAgent = req.getHeader("user-agent");
        Attach attach = this.attachService.findByMemberIdAndUuid(memberId, uuid);
        if (attach != null) {
            try {
                String encodeFileName = this.encodeFileName(attach.getOriginalFilename(), userAgent);
                resp.setHeader("Content-disposition", "attachment; filename=" + encodeFileName);
                resp.setContentType("application/octet-stream");
                FileUtils.copyFile(file, resp.getOutputStream());
            } catch (IOException e) {
                LOGGER.debug("下载文件时发生异常.", e);
                throw new BusinessException("文件不存在, 或者io操作有误");
            }
        }
    }

    private String encodeFileName(String fileName, String userAgent) throws UnsupportedEncodingException {
        if (userAgent.indexOf("MSIE") == -1) {
            //firefox, opera, chrome等
            return new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        } else {
            //IE
            return URLEncoder.encode(fileName, "UTF-8");
        }
    }
}
